package com.hava.web.serlvet;

import org.apache.commons.lang3.Validate;

import javax.servlet.ServletRequest;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by zhanpeng on 15-3-11.
 */
public class QueryRequestUtil {
    
    public static Map<String,Object> getParameter(ServletRequest request)
    {
        return getParameter(request,"");
    }
    
    public static Map<String,Object> getParameter(ServletRequest request,String prefix)
    {
        Validate.notNull(request,"Request must not be null");
        Enumeration<String> parameterNames = request.getParameterNames();
        
        //result init
        Map<String,Object> map = new TreeMap<String, Object>();
        if(prefix == null)
        {
            prefix = "";
        }
        
        while((parameterNames != null) && parameterNames.hasMoreElements())
        {
            String parameterName = parameterNames.nextElement();
            if(prefix.equals("") || parameterName.startsWith(prefix))
            {
                //get parameter values
                String [] values = request.getParameterValues(parameterName);
                //get unprefixed parameter name
                parameterName = parameterName.substring(prefix.length());
                
                if(values == null)
                {
                    //do nothing
                }
                else if(values.length == 0)
                {
                    //do nothing
                }
                else if(values.length == 1)
                {
                    map.put(parameterName,values[0]);
                }
                else if(values.length > 1)
                {
                    map.put(parameterName,values);
                }
            }
        }
        
        return map;
    }
    
    public static String encodeParameter(ServletRequest request,String prefix)
    {
        
        return encodeParameter(getParameter(request,prefix),prefix);
    }
    
    public static String encodeParameter(Map<String,Object> params,String prefix )
    {
        if((params == null) || params.isEmpty())
        {
            return "";
        }
        if(prefix == null)prefix = "";
        
        //using the stringbuilder to up string sub speed
        StringBuilder query = new StringBuilder();
        
        Iterator<Map.Entry<String,Object>> iterator = params.entrySet().iterator();
        while(iterator.hasNext())
        {
            Map.Entry<String,Object> entry = iterator.next();
            query.append(prefix).append(entry.getKey()).append('=').append(entry.getValue());
            
            if(iterator.hasNext())
                query.append('&');
        }
        
        return query.toString();
    }
}
